<?php

namespace app\core\exception;

use app\core\Response;
use HttpException;
use HttpResponseException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\ValidateException;

/**
 * 异常类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        ValidateException::class,
        BusinessException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param $exception
     * @return void
     */
    public function report($exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request $request
     * @param $e
     * @return \think\Response
     */
    public function render($request, $e): \think\Response
    {
        $response = Response::invoke();

        // 参数验证错误
        if ($e instanceof ValidateException) {
            $response->validateError($e->getMessage());
        }

        if ($e instanceof BusinessException) {
            $response->error($e->getMessage(), $e->getCode());
        }

        if (!$this->app->isDebug()) {
            if ($e instanceof HttpException || $e instanceof ModelNotFoundException || $e instanceof DataNotFoundException) {
                $response->systemError($e->getMessage());
            } else {
                $response->unknowError();
            }
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}
